package com.finance.rule.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.finance.base.constant.BaseConstants;
import com.finance.base.enums.OpearteEnum;
import com.finance.base.enums.StateEnum;
import com.finance.base.enums.TargetEnum;
import com.finance.base.exception.BaseException;
import com.finance.framework.controller.BaseController;
import com.finance.framework.controller.Result;
import com.finance.framework.lang.BeanUtils;
import com.finance.framework.lang.Page;
import com.finance.framework.lang.PageResultBO;
import com.finance.rule.bean.pojo.MajorRule;
import com.finance.rule.bean.pojo.MajorRuleList;
import com.finance.rule.service.IMajorRuleService;
import com.finance.rule.service.ISettingLogService;
import com.finance.system.bean.pojo.User;
import com.finance.system.request.MajorRuleListReq;
import com.finance.system.request.MajorRuleReq;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.text.ParseException;
import java.util.*;

/**
 * @Author: gly
 * @Date: Created in 2017-05-23
 */
@Controller
@RequestMapping("/rule/major")
public class MajorRuleController extends BaseController {
    @Resource
    private IMajorRuleService majorRuleService;

    @Resource
    private ISettingLogService settingLogService;

    private ObjectMapper objectMapper = new ObjectMapper();

    @RequestMapping("/index.htm")
    public String index() {
        return "rule/major/index";
    }

    @RequestMapping("/list")
    public Result list(MajorRuleListReq form) {
        Page page = Page.getInstance(form);
        MajorRuleList majorRuleList = new MajorRuleList();
        majorRuleList.setState(form.getState());
        page.setParams(majorRuleList);
        PageResultBO<MajorRule> resultBO = majorRuleService.listByPage(page);
        return getSuccessResult(resultBO);
    }

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String add() {
        return "rule/major/add";
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Result add(@Valid MajorRuleReq form) throws BaseException {
        User user = getAuthUser();
        if (user == null) {
            throw new BaseException(BaseConstants.ERR_UNKONW_USER);
        }
        MajorRule rule = convertMajorRule(form);
        rule.setCreateUid(user.getId());
        rule.setState(StateEnum.Valid.getState());
        if (!majorRuleService.supplierCodeExist(form.getSupplierCode())) {
            throw new BaseException(BaseConstants.ERR_SUPPLIER_CODE_EXISTS);
        }
        String ruleFlag="";
        if(StringUtils.isNotBlank(form.getParser())) {
            String[] ruleNames = form.getParser().split(".");
            if(ruleNames!=null&&ruleNames.length>0){
                ruleFlag = ruleNames[ruleNames.length-1];
            }
        }
        rule.setRuleFlag(ruleFlag);
        majorRuleService.add(rule);
        return getSuccessResult("添加主拖件规则成功");
    }

    @RequestMapping(value = "/update", method = RequestMethod.GET)
    public String update(String id, HttpServletRequest request) {
        MajorRule majorRule = majorRuleService.getById(Long.parseLong(id));
        request.setAttribute("majorRule", majorRule);
        return "rule/major/update";
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public Result update(String id, @Valid MajorRuleReq form) throws ParseException {
        if (StringUtils.isBlank(id)) {
            throw new BaseException(BaseConstants.ERR_INVALID_PARAMETER);
        }
        MajorRule oldRule = majorRuleService.getById(Long.parseLong(id));
        if (oldRule == null) {
            throw new BaseException(BaseConstants.ERR_NON_EXISTENT);
        }
        User user = getAuthUser();
        MajorRule rule = this.convertMajorRule(form);
        rule.setUpdateUid(user.getId());
        rule.setId(Long.parseLong(id));
        if (!majorRuleService.supplierCodeExist(form.getSupplierCode())
                && StringUtils.isNotBlank(form.getSupplierCode()) && StringUtils.isNotBlank(oldRule.getSupplierCode())
                && !form.getSupplierCode().equals(oldRule.getSupplierCode())) {
            throw new BaseException(BaseConstants.ERR_SUPPLIER_CODE_EXISTS);
        }
        String ruleFlag="";
        if(StringUtils.isNotBlank(form.getParser())) {
            String parser =form.getParser();
            String[] ruleNames = parser.split("\\.");
            if(ruleNames!=null&&ruleNames.length>0){
                ruleFlag = ruleNames[ruleNames.length-1];
            }
        }
        rule.setRuleFlag(ruleFlag);
        majorRuleService.update(rule);
        String oldValue = null;
        try {
            oldValue = objectMapper.writeValueAsString(oldRule);
        } catch (JsonProcessingException e) {
            logger.error(e.getMessage(), e);
        }
        settingLogService.addLog(user, OpearteEnum.UPDATE, TargetEnum.MAJOR_RULE_INFO, oldValue);

        return getSuccessResult("修改首拖件规则成功");
    }

    @RequestMapping(value = "/getdesc", method = RequestMethod.POST)
    public Result getDescription(String parser) {
        return getSuccessResult(majorRuleService.getDescription(parser));
    }

    private MajorRule convertMajorRule(MajorRuleReq form) {
        MajorRule rule = new MajorRule();
        try {
            BeanUtils.copyProperties(rule, form);
        } catch (Exception e) {
            throw new BaseException(BaseConstants.ERR_COPYBEAN);
        }
        return rule;
    }

    @RequestMapping(value = "/getinfos", method = RequestMethod.GET)
    public Result getRulesInfo() {
        List<Map<String, String>> rulesList = new ArrayList<Map<String, String>>();
        Map<String, String> rulesMap = new HashMap<String, String>();
            rulesMap.put("parser", "com.finance.rule.computer.AddressNameAcceptdayPostmanAnalyzer");
            rulesMap.put("description", "收件人名称、收件人地址、反馈小件员都一样，且发货在同一天（时段不同没关系）的");
            rulesMap.put("initJson", "{\"majorSuffix\":\"-1\"}");
            rulesList.add(rulesMap);
        rulesMap = new HashMap<String, String>();
            rulesMap.put("parser", "com.finance.rule.computer.AddressNameSignday3MetaAnalyzer");
            rulesMap.put("description", "三同合一 同收货地址 同收货电话 同妥投时间");
            rulesMap.put("initJson", "");
            rulesList.add(rulesMap);
        rulesMap = new HashMap<String, String>();
            rulesMap.put("parser", "com.finance.rule.computer.SameBusinessCodeAnalyzer");
            rulesMap.put("description", "订单号相同 选取运单号最小的为首件");
            rulesMap.put("initJson", "");
            rulesList.add(rulesMap);
        rulesMap = new HashMap<String, String>();
            rulesMap.put("parser", "com.finance.rule.computer.WaybillNumPrefixAnalyzer");
            rulesMap.put("description", "根据运单号的前缀 C开头为主件 D开头为拖件");
            rulesMap.put("initJson", "{\"prefixWaybill\": \"C\",\"prefixBusinessbill\": \"D\"}");
            rulesList.add(rulesMap);
        rulesMap = new HashMap<String, String>();
            rulesMap.put("parser", "com.finance.rule.computer.WaybillNumSuffixAnalyzer");
            rulesMap.put("description", "此解析类适用于以下三种场合\n根据运单号的后缀 以X1 X2 这种格式结尾 \n根据运单号的后缀 以-1 -2 -3这种格式结尾 \n 根据运单号的后缀 以-001 这种格式结尾 ");
            rulesMap.put("initJson", "{\"separator\":\"X\",\"majorSuffix\":\"X1\"}");
            rulesList.add(rulesMap);
        rulesMap = new HashMap<String, String>();
            rulesMap.put("parser", "com.finance.rule.computer.WaybillNumSeperatorSuffixAnalyzer");
            rulesMap.put("description", "此解析类适用于以下场合\n根据运单号的后缀 如果以-1这种格式结尾 \n非-1结尾运单皆为主件\n -2 ，-3为拖件,无-N则为主件");
            rulesMap.put("initJson", "{\"separator\":\"-\",\"majorSuffix\":\"1\"}");
            rulesList.add(rulesMap);
        rulesMap = new HashMap<String, String>();
            rulesMap.put("parser", "com.finance.rule.computer.WaybillNumNonSeperatorAnalyzer");
            rulesMap.put("description", "此解析类适用于以下场合\n根据运单号的后缀 运单号以-n结尾为拖件 其余均为主件  ");
            rulesMap.put("initJson", "{\"separator\":\"-\"}");
            rulesList.add(rulesMap);
        rulesMap = new HashMap<String, String>();
            rulesMap.put("parser", "com.finance.rule.computer.DangdangAnalyzer");
            rulesMap.put("description", "此解析类只适用于当当商家  ");
            rulesMap.put("initJson", "{\"separator\":\"-\"}");
            rulesList.add(rulesMap);
        return getSuccessResult(rulesList);
    }
    @RequestMapping(value = "/parserstransform", method = RequestMethod.GET)
    public Result parsersTransform() {
        List<Map<String, String>> rulesList = new ArrayList<Map<String, String>>();
        Map<String, String> rulesMap = new HashMap<String, String>();
        rulesMap.put("parser", "com.finance.rule.computer.AddressNameAcceptdayPostmanAnalyzer");
        rulesMap.put("exhibition", "收件人信息 配送员都一样 且发货在同一天");
        rulesList.add(rulesMap);
        rulesMap = new HashMap<String, String>();
        rulesMap.put("parser", "com.finance.rule.computer.AddressNameSignday3MetaAnalyzer");
        rulesMap.put("exhibition", "三同合一 同收货地址 同收货电话 同妥投时间");
        rulesList.add(rulesMap);
        rulesMap = new HashMap<String, String>();
        rulesMap.put("parser", "com.finance.rule.computer.SameBusinessCodeAnalyzer");
        rulesMap.put("exhibition", "订单号相同 选取运单号最小的为首件");
        rulesList.add(rulesMap);
        rulesMap = new HashMap<String, String>();
        rulesMap.put("parser", "com.finance.rule.computer.WaybillNumPrefixAnalyzer");
        rulesMap.put("exhibition", "运单号前缀匹配规则");
        rulesList.add(rulesMap);
        rulesMap = new HashMap<String, String>();
        rulesMap.put("parser", "com.finance.rule.computer.WaybillNumSuffixAnalyzer");
        rulesMap.put("exhibition", "运单号后缀匹配规则一 ");
        rulesList.add(rulesMap);
        rulesMap = new HashMap<String, String>();
        rulesMap.put("parser", "com.finance.rule.computer.WaybillNumSeperatorSuffixAnalyzer");
        rulesMap.put("exhibition", "运单号后缀匹配规则二");
        rulesList.add(rulesMap);
        rulesMap = new HashMap<String, String>();
        rulesMap.put("parser", "com.finance.rule.computer.WaybillNumNonSeperatorAnalyzer");
        rulesMap.put("exhibition", "运单号后缀匹配规则三");
        rulesList.add(rulesMap);
        rulesMap = new HashMap<String, String>();
        rulesMap.put("parser", "com.finance.rule.computer.DangdangAnalyzer");
        rulesMap.put("description", "当当首拖件规则");
        rulesList.add(rulesMap);
        return getSuccessResult(rulesList);
    }

}
